package com.example.BluetoothTest;

import javax.microedition.lcdui.Alert;
//import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;
import java.lang.String;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import java.io.IOException;
import javax.microedition.io.file.*;
import javax.microedition.io.Connector;
import java.io.DataOutputStream;


//import java.util.logging.*;
//import java.text.SimpleDateFormat;
import java.util.Timer;

public class BtInterfaceDisplay implements CommandListener{
	
    private BluetoothTestMidlet parent;
    private BTDeviceDiscovery btDiscovery;
    private Command exit;
    private Image onImage;
    private Timer BtRefresh = null;
    private int refresh_interval = 0;
    public List SearchedDevList;
    private FileConnection filecon = null;
    private DataOutputStream dis = null;
   // private String BtDeviceAddr;
    //private Logger log;
    //private static String path = "C:/Logs/Logpath/BtLog.txt";
   // private static  File filename = new File(path);
    public java.lang.String BtAddr;
    Display display;
    BtInterfaceDisplay(BluetoothTestMidlet parent)
    {
    	this.parent = parent;
    	btDiscovery = new BTDeviceDiscovery(this);
    	
    	exit = new Command("Exit", Command.EXIT, 2);
    	SearchedDevList = new List("Searching Devices...", List.IMPLICIT);
    	SearchedDevList.addCommand(exit);
        try {	
        	onImage = Image.createImage("/Icon.png");
        } catch (IOException e) {
            // provide off-screen image then
        	//do_alert("Image failed", 4000);
            onImage = createIndicatorImage(12, 12, 0, 255, 0);
        }
        //SearchedDevList.set(0, SearchedDevList.getString(0), onImage);
    	SearchedDevList.append("Searched Devices", onImage);
    	SearchedDevList.setCommandListener(this);
    	String v = System.getProperty("microedition.io.file.FileConnection.version" );
        if( v != null ){
        	try{
        		//String curURI = "c:/Test.txt" ;
        		//String str = "This is a bluetooth test";
        		filecon = (FileConnection)Connector.open("file://localhost/E:/Test.txt",Connector.READ_WRITE); 
        		if(!filecon.exists())
        		{
        			filecon.create();
        			this.do_alert("create file", 4000);
        		}
        		//filecon.close();
        		//OutputStream out = conn.openOutputStream();
        	}catch(Exception e){
        	}
       } 
        else {
    	   this.do_alert("FCOP not available", 4000);
        }
        BtRefresh = new Timer();
        //refresh_interval = Integer.parseInt(parent.txtField.getString());
        refresh_interval = 60000 * parent.gauge.getValue();
        //do_alert(parent.txtField.getString(), 4000);
    	BtRefresh.schedule(btDiscovery, 0, refresh_interval);
    	//SearchedDevList.append("Searching...", null);
    	display = Display.getDisplay(parent);
    	display.setCurrent(SearchedDevList);
    	//FindDevices();
    }
    
    public void commandAction(Command c, Displayable d) {
    	if (c == exit){                                              //exit triggered from the main form
    		try{
    			if(filecon != null){
    				filecon.close();
    				filecon = null;}
    			if(dis != null){
    				dis.close();}	
    		}catch(Exception e){
    		}
    		destroy();
            parent.show();  
        }
    	
    }
    
    /** Destroys this component. */
    void destroy() {
        // finalize the image server work
    	if(btDiscovery.BtDiscoveryThread != null)
    	{
    		//btDiscovery.BtDiscoveryThread.sleep(1000);
    		btDiscovery.BtDiscoveryThread = null;
    	}
    	SearchedDevList.deleteAll();
    	BtRefresh.cancel();
    	btDiscovery.cancel();
    }
    
    void updateDeviceList(String BtDeviceAddr)
    {
	    //Date currentTime = new Date();
	    //SimpleDateFormat Timeformat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
    	//this.do_alert("updateDeviceList...", 400);
    	//this.do_alert(Timeformat.format(currentTime), 400);
    	//this.do_alert(BtAddr, 400);
    	//log = Logger.getLogger(BtInterfaceDisplay.class.getName());
    	//log.info(BtDeviceAddr);
    	try{
    		dis = new DataOutputStream(filecon.openOutputStream(filecon.fileSize()));
    		//dis = filecon.openDataOutputStream();
    		//dis.writeChars("\n\n");
    		//dis.writeChars(BtDeviceAddr);
    		//dis.writeChars("\r");
    		//dis.writeUTF(BtDeviceAddr);
    		//dis.writeChars("\n");
    		//dis.flush();
    		dis.writeUTF(BtDeviceAddr+"\r\n");
    		dis.flush();
    		dis.close();
    		dis = null;
    	}
    	catch(Exception e){
    	}
    	//SearchedDevList.setTitle("Searched Device");
    	/*try{
    		 onImage = Image.createImage("/Icon.png");
    	}catch(Exception e){
    	}*/
    	SearchedDevList.append(BtDeviceAddr, onImage);
    	display = Display.getDisplay(parent);
    	display.setCurrent(SearchedDevList);
    }
    
    private Image createIndicatorImage(int w, int h, int r, int g, int b) {
        Image res = Image.createImage(w, h);
        Graphics gc = res.getGraphics();
        gc.setColor(r, g, b);
        gc.fillRect(0, 0, w, h);

        return res;
    }
   /* public void getBtAddr(String BtAddr)
    {
    	BtDeviceAddr = BtAddr;
    }*/
    void do_alert(String msg,int time_out){
        if (display.getCurrent() instanceof Alert ){
            ((Alert)display.getCurrent()).setString(msg);
            ((Alert)display.getCurrent()).setTimeout(time_out);
        }else{
            Alert alert = new Alert("Bluetooth");
            alert.setString(msg);
            alert.setTimeout(time_out);
            display.setCurrent(alert);
        }
    }
}
